#!/bin/bash

if [ ! $# -eq 2 ]
then
    echo "usage : start_django_project projectname project.virtual.host"
        exit
fi

if [ ! -e /usr/local/django ] 
then
        mkdir -p -v /usr/local/django
else
        echo "/usr/local/django already exists"
fi

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

pushd /usr/local/django

if [ -e /usr/local/django/$1 ]
then
        echo "Project $1 already exists in /usr/local/django/ !"
        exit 0
else
        django-admin.py startproject $1
        cd $1
        mkdir templates media static
        pushd $1
        sed -i '1 a import os' settings.py
        sed -i '2 a ROOT_PATH = os.path.dirname(os.path.dirname(__file__))' settings.py
        sed -i 's/django\.db\.backends\./&sqlite3/' settings.py
        sed -i "/DATABASES/,/}/ s/\('NAME': \)\(''\)/\1os\.path\.join(ROOT_PATH\,'sqlite\.db')/" settings.py
        sed -i "s/\(TIME_ZONE = '\)\(.*\)\('\)/\1Europe\/Brussels\3/" settings.py
        sed -i "s/\(LANGUAGE_CODE = '\)\(.*\)\('\)/\1fr-fr\3/" settings.py
        sed -i "s/\(MEDIA_ROOT = \)\(.*\)$/\1os\.path\.join(ROOT_PATH\,'media\/')/" settings.py
        sed -i "s/\(MEDIA_URL = \)\(.*\)$/\1'\/media\/'/" settings.py
        sed -i "s/\(STATIC_ROOT = \)\(.*\)$/\1os\.path\.join(ROOT_PATH\,'static\/')/" settings.py
        sed -i "/TEMPLATE_DIRS/,/INSTALLED_APPS/ s#^)#    os.path.join(ROOT_PATH,'templates'),\n&#" settings.py
        sed -i "/INSTALLED_APPS/,/^)/ s/# *\('django\)/\1/" settings.py
        
        sed -i "/# Uncomment the next two lines/{N;N;s/# //2g}" urls.py
        sed -i "/^urlpatterns/,/^)/ s/\([ \t]*\)# *\(url(r'^admin.*\)$/\1\2/" urls.py
        
        popd

    $SCRIPT_DIR/configure_httpd_for_django_project.sh $1 $2
    
fi
